package com.jeeplus.common.utils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 生成以“YFJS”开头+日期时间+0000开始的4位数字
 */
public class PrimaryGenerater {

	private static final String SERIAL_NUMBER = "XXXX"; // 流水号格式
	private static PrimaryGenerater primaryGenerater = null;

	private PrimaryGenerater() {
	}

	/**
	 *  取得PrimaryGenerater的单例实现
	 *
	 * @return
	 */
	public static PrimaryGenerater getInstance() {
		if (primaryGenerater == null) {
			synchronized (PrimaryGenerater.class) {
				if (primaryGenerater == null) {
					primaryGenerater = new PrimaryGenerater();
				}
			}
		}
		return primaryGenerater;
	}

	/**
	 * 生成下一个编号
	 * String head 以什么开头，比如:YFJS
	 * String sno	在数据库中查找最大单号
	 */
	public synchronized String generaterNextNumber(String head,String sno) {
		//String head = "YFJS";
		String id = null;
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		if (sno == null) {	//如果单号为空，则从0001开始
			id = head+ formatter.format(date) + "0001";
		} else {	//如果单号不为空，则截取后四位每次加1
			int count = SERIAL_NUMBER.length();
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < count; i++) {
				sb.append("0");
			}
			DecimalFormat df = new DecimalFormat("0000");
			String temp = sno.substring(18,22);
			//System.out.println("temp :"+temp);
			id = head + formatter.format(date) + df.format(1+Integer.parseInt(temp));
		}
		return id;
	}
	
	/*public static void main(String[] args) {
		String id = PrimaryGenerater.getInstance().generaterNextNumber(null);
		System.out.println(id);
	}*/
}
